package com.test.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.test.entity.User;
import com.test.service.UserService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询所有excel列表
     *
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model) {
        List<User> list = userService.findAll();
        model.addAttribute("list", list);
        return "index";
    }

    /**
     * 导入excel文件
     *
     * @param excelFile
     * @return
     * @throws Exception
     */
    @RequestMapping("/import")
    public String excelImport(MultipartFile excelFile) throws Exception {
        userService.saveAll(excelFile);
        return "redirect:/user/findAll";
    }

    /**
     * excel文件导出
     */
    @Value("${upload.dir}")
    private String realPath;
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //先查询到要导出的excel数据
        List<User> userList = userService.findAll();
        //数据库保存的图片名,并不是图片路径,需要获取路径凭借图片名
        userList.forEach(user->{
            user.setPhoto(realPath + "/" +user.getPhoto());
        });
        ExportParams exportParams = new ExportParams();  //导出的excel相关配置
        exportParams.setTitle("用户信息表");  //导出excel的第一行标题名字
        exportParams.setSheetName("用户信息sheet");  //导出的excel的sheet名称
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, userList);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("用户列表.xlsx", "utf-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        //关闭流
        outputStream.close();
        workbook.close();
    }
}
